package com.jsu.controller;

import com.alipay.api.AlipayApiException;

import com.jsu.config.MessageProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.model.pay.pojo.AliPay;
import org.example.model.pay.pojo.Payment;
import org.example.model.common.dtos.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.jsu.service.PaymentService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class AliPayController {

   @Autowired
   private PaymentService paymentService;


   @ApiOperation(value = "支付请求")
   @GetMapping("/pay")
   public void pay(AliPay aliPay, HttpServletResponse httpResponse) {
      try {
         paymentService.pay(aliPay,httpResponse);
      } catch (AlipayApiException | IOException e) {
         throw new RuntimeException(e);
      }
   }

   @ApiOperation(value = "支付成功信息异步回调")
   @PostMapping("/notify")  // 注意这里必须是POST接口
   public ResponseResult payNotify(HttpServletRequest request) throws Exception {
         return paymentService.payNotify(request);
   }

   @ApiOperation(value = "退款操作")
   @GetMapping("/toRefund")
   public void toRefund(HttpServletResponse response, Integer paymentId,Float amount){
      try {
         paymentService.toRefund(response, paymentId,amount);
      } catch (IOException e) {
         throw new RuntimeException(e);
      }
   }

   @ApiOperation(value = "活动订单创建，但不支付，响应数据为支付表主键id")
   @PostMapping("/addPayment")
   public ResponseResult addPayment(@RequestBody Payment payment){
      log.info("addPayment: payment={}", payment);
      return paymentService.createPayment(payment);
   }

   @ApiOperation(value = "活动订单列表")
   @GetMapping("/paymentList")
   public ResponseResult paymentList(Integer userId){
      return paymentService.paymentList(userId);
   }


   @Autowired
   private MessageProducer producer;
   @GetMapping("/testDelay/{id}")
   public String send(@PathVariable("id") Integer id){
      producer.sendDelayQueue(id,1000 * 5);
      return "ok";
   }

}

